<template>
  <div class="checkbox">
    <el-checkbox
      v-model="check"
      class="checkbox-all"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
    >
      全选
    </el-checkbox>
    <el-checkbox-group v-model="comValue" :disabled="disabled" @change="change">
      <el-checkbox v-for="item in options" :key="item.id" :value="item.code">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script setup>
import { dictStore } from '@/pinia/modules/dict'
const dictStoreData = dictStore()
const emit = defineEmits(['update:modelValue', 'changeCheckBox'])
const props = defineProps({
  modelValue: {
    type: String,
    default() {
      return ''
    }
  },
  dictCode: {
    require: true,
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

let comValue = ref([])
comValue.value = props.modelValue ? props.modelValue.split(',') : []
let check = ref(false)
let isIndeterminate = ref(false)

const options = computed(() => {
  return formatDictCode()
})

watch(
  () => props.modelValue,
  val => {
    if (val) {
      comValue.value = val.split(',')
    } else {
      comValue.value = []
    }
  }
)

watch(
  () => comValue.value,
  (newVal, oldVal) => {
    console.log('触发', newVal, oldVal, newVal === oldVal)
    if (newVal !== oldVal) {
      const arr = JSON.parse(JSON.stringify(comValue.value))
      arr.sort((a, b) => {
        return a - b
      })
      const str = arr.join(',')
      emit('update:modelValue', str)
    }
  }
)

const formatDictCode = () => {
  const code = props.dictCode
  const target = dictStoreData.dict?.find(item => item.code === code)
  check.value = comValue.value.length === target.children.length
  isIndeterminate.value =
    comValue.value.length > 0 && comValue.value.length < target.children.length
  return target.children
}

const change = val => {
  const str = val.join(',')
  console.log('str', val.length === options.value.length)
  check.value = val.length === options.value.length
  isIndeterminate.value = val.length > 0 && val.length < options.value.length
  emit('changeCheckBox', str)
}

const handleCheckAllChange = val => {
  console.log(val)
  comValue.value = val ? options.value.map(item => item.code) : []
  const str = comValue.value.length > 0 ? comValue.value.join(',') : ''
  emit('changeCheckBox', str)
  isIndeterminate.value = false
}
</script>

<style lang="scss" scoped>
.checkbox {
  display: flex;

  .checkbox-all {
    margin-right: 30px;
  }
}
</style>
